package cn.kgc.hotel.controller;

import cn.kgc.hotel.entity.*;
import cn.kgc.hotel.service.RoomService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/room")
//@CrossOrigin
public class RoomController {

    @Resource
    private RoomService roomService;

    private String[] dates;


    //按入住日期和关键字，查询所有可预订房型信息
    @RequestMapping("/searchRoomType")
    List<RoomType> searchRoomType(String keyWord, String datesString) {
        System.out.println("接受到的datesString字符串:" + datesString);
        //日期字符串不存在或为空时，默认设置为当天,并转化为数组
        if (null == datesString || datesString.isEmpty()) {
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String s = simpleDateFormat.format(date);
            dates = new String[]{s};
        } else {
            //日期字符串不为空时，转化为数组
            dates = datesString.split(",");
            //开始日期等于结束日期时，数组中只填一个日期
            if (dates[0].equals(dates[1])) {
                dates = new String[]{dates[0]};
            } else {
                //根据开始日期和结束日期，补全中间日期，并转为数组
                try {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date startDate = simpleDateFormat.parse(dates[0]);
                    Date endDate = simpleDateFormat.parse(dates[1]);
                    List<String> dateList = new ArrayList<>();
                    dateList.add(dates[0]);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startDate);
                    while (endDate.after(calendar.getTime())) {
                        //日历每次加一天
                        calendar.add(Calendar.DAY_OF_MONTH, 1);
                        //将日历放入List
                        dateList.add(simpleDateFormat.format(calendar.getTime()));
                    }
                    //List转为数组。toArray(T[] a)转化为a类型数组，长度不够会自己增加。这里也可写成toArray(new String[0])。
                    dates = dateList.toArray(dates);

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }

        for (int i = 0; i < dates.length; i++) {
            System.out.println("最终的日期遍历,第" + i + "个日期：" + dates[i]);
        }

        return roomService.searchRoomType(dates, keyWord);
    }

    //按房型ID和入住日期查询房型信息
    @RequestMapping("/searchRoomTypeById")
    RoomType searchRoomTypeById(Integer typeId, String datesString) {
        //日期字符串不存在或为空时，默认设置为当天,并转化为数组
        if (null == datesString || datesString.isEmpty()) {
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String s = simpleDateFormat.format(date);
            dates = new String[]{s};
        } else {
            //日期字符串不为空时，转化为数组
            dates = datesString.split(",");
            //开始日期等于结束日期时，数组中只填一个日期
            if (dates[0].equals(dates[1])) {
                dates = new String[]{dates[0]};
            } else {
                //根据开始日期和结束日期，补全中间日期，并转为数组
                try {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date startDate = simpleDateFormat.parse(dates[0]);
                    Date endDate = simpleDateFormat.parse(dates[1]);
                    List<String> dateList = new ArrayList<>();
                    dateList.add(dates[0]);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startDate);
                    while (endDate.after(calendar.getTime())) {
                        //日历每次加一天
                        calendar.add(Calendar.DAY_OF_MONTH, 1);
                        //将日历放入List
                        dateList.add(simpleDateFormat.format(calendar.getTime()));
                    }
                    //List转为数组。toArray(T[] a)转化为a类型数组，长度不够会自己增加。这里也可写成toArray(new String[0])。
                    dates = dateList.toArray(dates);

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        for (int i = 0; i < dates.length; i++) {
            System.out.println("最终的日期遍历,第" + i + "个日期：" + dates[i]);
        }
        return roomService.searchRoomTypeById(typeId, dates);
    }

    //按房型ID和入住日期查询空房间
    @RequestMapping("/searchRooms")
    List<Room> searchRooms(Integer typeId, String datesString) {
        //日期字符串不存在或为空时，默认设置为当天,并转化为数组
        if (null == datesString || datesString.isEmpty()) {
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String s = simpleDateFormat.format(date);
            dates = new String[]{s};
        } else {
            //日期字符串不为空时，转化为数组
            dates = datesString.split(",");
            //开始日期等于结束日期时，数组中只填一个日期
            if (dates[0].equals(dates[1])) {
                dates = new String[]{dates[0]};
            } else {
                //根据开始日期和结束日期，补全中间日期，并转为数组
                try {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date startDate = simpleDateFormat.parse(dates[0]);
                    Date endDate = simpleDateFormat.parse(dates[1]);
                    List<String> dateList = new ArrayList<>();
                    dateList.add(dates[0]);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startDate);
                    while (endDate.after(calendar.getTime())) {
                        //日历每次加一天
                        calendar.add(Calendar.DAY_OF_MONTH, 1);
                        //将日历放入List
                        dateList.add(simpleDateFormat.format(calendar.getTime()));
                    }
                    //List转为数组。toArray(T[] a)转化为a类型数组，长度不够会自己增加。这里也可写成toArray(new String[0])。
                    dates = dateList.toArray(dates);

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        for (int i = 0; i < dates.length; i++) {
            System.out.println("最终的日期遍历,第" + i + "个日期：" + dates[i]);
        }
        return roomService.searchRooms(typeId, dates);
    }

    //房间预订,房间订单表room_reserve insert
    @RequestMapping("/roomReserve")
    Boolean roomReserve(@RequestBody String paramsFromVueByAxiosPost) {
        //测试，输出接收到的参数
        System.out.println("接收到的paramsFromVueByAxiosPost:" + paramsFromVueByAxiosPost);

        //字符串转化为JSON对象
        JSONObject params = JSON.parseObject(paramsFromVueByAxiosPost);

        //获取roomReserveObj属性值
        RoomReserve roomReserve = params.getObject("roomReserveObj", RoomReserve.class);

        //获取datesString属性值
        String datesString = params.getString("datesString");
        System.out.println("datesString:" + datesString);
        //获取roomIds属性值
        JSONArray roomIdsJSONArray = params.getJSONArray("roomIds");
        int[] roomIds = new int[roomIdsJSONArray.size()];
        for (int i = 0; i < roomIdsJSONArray.size(); i++) {
            roomIds[i] = roomIdsJSONArray.getInteger(i);
            System.out.println("roomIds[" + i + "]:" + roomIds[i]);
        }
        //获取roomCustomers属性
        JSONArray roomCustomersJSONArray = params.getJSONArray("roomCustomers");
        List<RoomCustomer> roomCustomerList = new ArrayList<>();
        for (int i = 0; i < roomCustomersJSONArray.size(); i++) {
            JSONObject jsonObject1 = roomCustomersJSONArray.getJSONObject(i);
            RoomCustomer roomCustomer = jsonObject1.toJavaObject(RoomCustomer.class);
            roomCustomerList.add(roomCustomer);
            System.out.println(roomCustomerList.get(i).getRoomId());
            System.out.println(roomCustomerList.get(i).getCustomer().getName());
        }


        //设置订单对象的属性
        roomReserve.setPeopleType(1);
        roomReserve.setStateId(1);
        roomReserve.setOnline(1);

        //时间格式
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //获取当前系统日期对象,赋值给订单对象的time属性
        Date date = new Date();
        roomReserve.setTime(timeFormat.format(date));

        //订单ID第一步：将时间戳转化为订单ID
        SimpleDateFormat s = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        StringBuilder reserveId = new StringBuilder(s.format(date));
        Random random = new Random();

        //订单ID第二步：订单ID后加6位随机数
        for (int i = 0; i < 6; i++) {
            reserveId.append(random.nextInt(10));
        }

        //订单ID第三步：订单ID后加修改人类型和修改人ID，形成最终的订单ID
        reserveId.append(roomReserve.getPeopleType());
        reserveId.append(roomReserve.getPeopleId());
        roomReserve.setReserveId(reserveId.toString());

        //测试用的，输出订单对象的所有属性
        System.out.println("房间订单ID：" + roomReserve.getReserveId());
        System.out.println("修改时间：" + roomReserve.getTime());
        System.out.println("修改人类型：" + roomReserve.getPeopleType());
        System.out.println("修改人ID：" + roomReserve.getPeopleId());
        System.out.println("入住日期：" + roomReserve.getStartDate());
        System.out.println("退房日期：" + roomReserve.getEndDate());
        System.out.println("留言：" + roomReserve.getNotes());
        System.out.println("订单状态ID：" + roomReserve.getStateId());
        System.out.println("线上：" + roomReserve.getOnline());

        //将roomIds转化为数组
       /* String[] roomIdList = new String[1];
        if (null != roomIds && "" != roomIds) {
            roomIdList = roomIds.split(",");
            //测试用，遍历房间ID
            for (int i = 0; i < roomIdList.length; i++) {
                System.out.println("遍历房间ID，第" + i + "个ID：" + roomIdList[i]);
            }
        } else {
            return 0;
        }*/


        //将datesString转化为数组，并补全中间日期
        if (null != datesString && !datesString.isEmpty()) {
            //将datesString转化为数组
            dates = datesString.split(",");
            //开始日期等于结束日期时，数组中只填一个日期
            if (dates[0].equals(dates[1])) {
                dates = new String[]{dates[0]};
            } else {
                //根据开始日期和结束日期，补全中间日期，并转为数组
                try {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date startDate = simpleDateFormat.parse(dates[0]);
                    Date endDate = simpleDateFormat.parse(dates[1]);
                    List<String> dateList = new ArrayList<>();
                    dateList.add(dates[0]);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startDate);
                    while (endDate.after(calendar.getTime())) {
                        //日历每次加一天
                        calendar.add(Calendar.DAY_OF_MONTH, 1);
                        //将日历放入List
                        dateList.add(simpleDateFormat.format(calendar.getTime()));
                    }
                    //List转为数组。toArray(T[] a)转化为a类型数组，长度不够会自己增加。这里也可写成toArray(new String[0])。
                    dates = dateList.toArray(dates);
                    //测试用，遍历最终日期数组
                    for (int i = 0; i < dates.length; i++) {
                        System.out.println("遍历最终日期数组，第" + i + "个日期：" + dates[i]);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        } else {
            return false;
        }
        //封装房间日期对象集合
        List<RoomDate> roomDateList = new ArrayList<>();
        for (int roomId : roomIds) {
            System.out.println("roomId:" + roomId);
            for (String d : dates) {
                RoomDate roomDate = new RoomDate();
                System.out.println("d:" + d);
                roomDate.setRoomId(roomId);
                roomDate.setDate(d);
                roomDate.setStateId(1);
                System.out.println(roomDate.getRoomId() + "," + roomDate.getDate() + "," + roomDate.getStateId());
                roomDateList.add(roomDate);
            }
        }

        for (RoomDate roomDate1 : roomDateList) {
            System.out.println(roomDate1.getRoomId() + "," + roomDate1.getDate() + "," + roomDate1.getStateId());
        }

        //房间住客对象集合设置属性值;放入集合
        List<Customer> customerList = new ArrayList<>();
        for (RoomCustomer roomCustomer : roomCustomerList) {
            roomCustomer.setReserveId(reserveId.toString());
            customerList.add(roomCustomer.getCustomer());
        }

        //调用业务层
        Boolean flag = roomService.roomReserve(roomReserve, roomDateList,
                roomCustomerList, customerList);
        System.out.println("flag:" + flag);
        return flag;
    }

    //查询房间预订
    @RequestMapping("/searchRoomReserve")
    List<RoomReserve> searchRoomReserve(int userId) {
        return roomService.searchRoomReserve(userId);

    }

    //修改房间预订
    @RequestMapping("/updateRoomReserve")
    Boolean updateRoomReserve(@RequestBody RoomReserve roomReserve) {
        System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAA" + roomReserve.getReserveId());
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        roomReserve.setTime(time);
        return roomService.updateRoomReserve(roomReserve);
    }

    //取消房间预订
    @RequestMapping("/cancelRoomReserve")
    Boolean cancelRoomReserve(@RequestBody RoomReserve roomReserve) {
        //获取当前系统时间并按相应格式赋值给属性time
        Date date = new Date();
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        roomReserve.setTime(timeFormat.format(date));
        //设置订单状态ID
        roomReserve.setStateId(2);
        return roomService.cancelRoomReserve(roomReserve);
    }


}
